<?php

namespace App\Http\Controllers;

use Uuid;
use Redis;
use LucaDegasperi\OAuth2Server\Authorizer;

class CommentController extends CommonController
{
    public function __construct(Authorizer $authorizer)
    {
        parent::__construct($authorizer);

        $this->middleware('oauth', ['except' => ['todo']]);
        $this->middleware('validation');
    }

    private static $_validate = [
        'reply' => [
            'content' => 'required',
        ],
    ];

    public function favour($articleId, $commentId)
    {
        $uid = $this->authorizer->getResourceOwnerId();

        $addFlag = Redis::sadd("users:{$uid}:favours", $commentId);

        $this->parameterArr = [$addFlag, 1, $articleId];
        $this->deltaFavour($commentId);

        return $this->favourResponse($commentId);
    }

    public function unfavour($articleId, $commentId)
    {
        $uid = $this->authorizer->getResourceOwnerId();

        $remFlag = Redis::srem("users:{$uid}:favours", $commentId);

        $this->parameterArr = [$remFlag, -1, $articleId];
        $this->deltaFavour($commentId);

        return $this->favourResponse($commentId);
    }

    protected function deltaFavour($commentId)
    {
        list($switch, $delta, $articleId) = $this->parameterArr;

        if ($switch !== 1) {
            return;
        }

        Redis::zincrby("sisi_articles:{$articleId}:comments:favours", $delta, $commentId);

        Redis::hincrby("comments:{$commentId}", 'favours', $delta);
    }

    protected function favourResponse($commentId)
    {
        $favours = Redis::hget("comments:{$commentId}", 'favours');

        if ($favours === null) {
            $favours = '0';
        }

        return [
            'comment_id' => $commentId,
            'favours'    => $favours,
        ];
    }

    public function reply($commentId)
    {
        $uid  = $this->authorizer->getResourceOwnerId();
        $user = $this->fetchUser($uid);

        $content = request('content');

        $replyId = Uuid::generate(4)->string;

        $hashData = [
            'id'         => $replyId,
            'user_id'    => $uid,
            'content'    => $content,
            'created_at' => date('Y-m-d H:i:s'),
        ];

        Redis::hmset("replies:{$replyId}", $hashData);

        Redis::zadd("comments:{$commentId}:replies", time(), $replyId);

        return array_merge($hashData, ['user' => $user]);
    }
}